package com.security.frame.core.social.weibo.api;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.security.frame.core.social.qq.api.QQUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取微博会员信息
 *
 * @author wangjie
 * @version V1.0
 * @date 2019/11/18
 */
@Slf4j
public class WeiboImpl extends AbstractOAuth2ApiBinding implements Weibo {

    /**
     * 获取微博uid请求地址
     */
    private static final String URL_GET_UID = "https://api.weibo.com/2/account/get_uid.json?access_token=%s";

    /**
     * 获取微博会员信息地址
     */
    private static final String URL_GET_USERINFO = "https://api.weibo.com/2/users/show.json?access_token=%s&uid=%s";

    private String uid;

    private String accessToken;

    private ObjectMapper objectMapper = new ObjectMapper();

    public WeiboImpl(String accessToken){

        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);

        this.accessToken = accessToken;

        String url = String.format(URL_GET_UID, accessToken);

        String result = getRestTemplate().getForObject(url, String.class);
        log.info("【获得微博会员uid】:{}",result);
        uid = StringUtils.substringBetween(result, ":", "}");
        log.info("【获得微博会员uid】:{}",uid);


    }

    @Override
    public WeiboUserInfo getUserInfo() {

        if(StringUtils.isBlank(accessToken) || StringUtils.isBlank(uid)){
            log.info("【获取微博会员信息异常，必要参数为空】accessToken:{},uid:{}",accessToken,uid);
            throw new RuntimeException("获取微博用户信息失败，必要参数为空");
        }

        String url = String.format(URL_GET_USERINFO, accessToken, uid);
        String result = getRestTemplate().getForObject(url, String.class);

        log.info("【获得微博会员信息】:{}",result);

        WeiboUserInfo userInfo = new WeiboUserInfo();
        try {
            Map mapType = JSON.parseObject(result,Map.class);
            userInfo.setId((String) mapType.get("idstr"));
            userInfo.setName((String) mapType.get("name"));
            userInfo.setProfileImageUrl((String) mapType.get("profile_image_url"));
        } catch (Exception e) {
            throw new RuntimeException("获取用户信息失败", e);
        }
        return userInfo;
    }
}
